<template>
  <view class="page-container">
    <!-- 时间筛选 -->
    <view class="filter-bar">
      <view class="time-filter">
        <uni-datetime-picker 
          v-model="dateRange" 
          type="daterange"
          :clear-icon="false"
          rangeSeparator="至"
        >
          <template v-slot:default="{ value }">
            <view class="date-input">
              <uni-icons type="calendar" size="16" color="#999"></uni-icons>
              <text class="date-text">{{ value || '选择时间范围' }}</text>
            </view>
          </template>
        </uni-datetime-picker>
      </view>
      <button class="filter-btn" @click="handleFilter">筛选</button>
    </view>

    <!-- 概览统计卡片 -->
    <view class="overview-stats">
      <view class="stats-grid">
        <view class="stats-card">
          <view class="stats-icon coupon-icon">
            <uni-icons type="gift" size="24" color="#fff"></uni-icons>
          </view>
          <view class="stats-content">
            <text class="stats-value">{{ overviewData.total_coupons || 0 }}</text>
            <text class="stats-label">优惠券总数</text>
          </view>
        </view>
        
        <view class="stats-card">
          <view class="stats-icon issued-icon">
            <uni-icons type="paperplane" size="24" color="#fff"></uni-icons>
          </view>
          <view class="stats-content">
            <text class="stats-value">{{ overviewData.issued_count || 0 }}</text>
            <text class="stats-label">已发放</text>
          </view>
        </view>
        
        <view class="stats-card">
          <view class="stats-icon used-icon">
            <uni-icons type="checkmarkempty" size="24" color="#fff"></uni-icons>
          </view>
          <view class="stats-content">
            <text class="stats-value">{{ overviewData.used_count || 0 }}</text>
            <text class="stats-label">已使用</text>
          </view>
        </view>
        
        <view class="stats-card">
          <view class="stats-icon rate-icon">
            <uni-icons type="bars" size="24" color="#fff"></uni-icons>
          </view>
          <view class="stats-content">
            <text class="stats-value">{{ overviewData.usage_rate || '0%' }}</text>
            <text class="stats-label">使用率</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 图表统计 -->
    <view class="chart-section">
      <view class="section-title">
        <text>趋势分析</text>
        <view class="chart-tabs">
          <text 
            v-for="tab in chartTabs" 
            :key="tab.value"
            class="chart-tab"
            :class="{ active: activeChartTab === tab.value }"
            @click="switchChartTab(tab.value)"
          >
            {{ tab.label }}
          </text>
        </view>
      </view>
      
      <view class="chart-container">
        <view v-if="chartData.length === 0" class="empty-chart">
          <uni-icons type="bars" size="48" color="#ccc"></uni-icons>
          <text class="empty-text">暂无数据</text>
        </view>
        <view v-else class="chart-content">
          <!-- 这里可以集成图表库，如uCharts -->
          <view class="simple-chart">
            <view 
              v-for="(item, index) in chartData" 
              :key="index"
              class="chart-bar"
              :style="{ height: getBarHeight(item.value) + 'px' }"
            >
              <view class="bar-value">{{ item.value }}</view>
            </view>
          </view>
          <view class="chart-labels">
            <text 
              v-for="(item, index) in chartData" 
              :key="index"
              class="chart-label"
            >
              {{ item.label }}
            </text>
          </view>
        </view>
      </view>
    </view>

    <!-- 详细统计 -->
    <view class="detail-stats">
      <view class="section-title">详细统计</view>
      
      <!-- 优惠券类型统计 -->
      <view class="stats-item">
        <view class="item-header">
          <text class="item-title">按类型统计</text>
        </view>
        <view class="item-content">
          <view 
            v-for="item in typeStats" 
            :key="item.type"
            class="stat-row"
          >
            <view class="stat-info">
              <text class="stat-name">{{ getCouponTypeText(item.type) }}</text>
              <text class="stat-desc">{{ item.count }}张 · 使用率{{ item.usage_rate }}</text>
            </view>
            <view class="stat-progress">
              <view 
                class="progress-bar" 
                :style="{ width: item.usage_rate }"
              ></view>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 门店统计 -->
      <view class="stats-item">
        <view class="item-header">
          <text class="item-title">门店核销排行</text>
        </view>
        <view class="item-content">
          <view 
            v-for="(item, index) in storeStats" 
            :key="item.store_id"
            class="rank-row"
          >
            <view class="rank-number" :class="getRankClass(index)">
              {{ index + 1 }}
            </view>
            <view class="rank-info">
              <text class="rank-name">{{ item.store_name }}</text>
              <text class="rank-desc">核销{{ item.verify_count }}张</text>
            </view>
            <text class="rank-amount">¥{{ (item.total_amount || 0) / 100 }}</text>
          </view>
        </view>
      </view>
      
      <!-- 时间段统计 -->
      <view class="stats-item">
        <view class="item-header">
          <text class="item-title">使用时段分布</text>
        </view>
        <view class="item-content">
          <view class="time-distribution">
            <view 
              v-for="item in timeStats" 
              :key="item.hour"
              class="time-bar"
            >
              <view class="time-label">{{ item.hour }}:00</view>
              <view class="time-progress">
                <view 
                  class="time-fill" 
                  :style="{ height: getTimeBarHeight(item.count) + '%' }"
                ></view>
              </view>
              <view class="time-count">{{ item.count }}</view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { onLoad, onPullDownRefresh } from '@dcloudio/uni-app';
import { fetchCouponStatistics } from '@/api/coupon';
import { getCouponTypeText } from '@/utils/coupon';
import moment from 'moment';

interface OverviewData {
  total_coupons: number;
  issued_count: number;
  used_count: number;
  usage_rate: string;
}

interface ChartData {
  label: string;
  value: number;
}

interface TypeStat {
  type: number;
  count: number;
  usage_rate: string;
}

interface StoreStat {
  store_id: number;
  store_name: string;
  verify_count: number;
  total_amount: number;
}

interface TimeStat {
  hour: number;
  count: number;
}

const dateRange = ref<string[]>([]);
const loading = ref(false);
const activeChartTab = ref('issued');

const overviewData = reactive<OverviewData>({
  total_coupons: 0,
  issued_count: 0,
  used_count: 0,
  usage_rate: '0%'
});

const chartData = ref<ChartData[]>([]);
const typeStats = ref<TypeStat[]>([]);
const storeStats = ref<StoreStat[]>([]);
const timeStats = ref<TimeStat[]>([]);

const chartTabs = [
  { label: '发放量', value: 'issued' },
  { label: '使用量', value: 'used' },
  { label: '核销额', value: 'amount' }
];

// 初始化日期范围为最近7天
const initDateRange = () => {
  const endDate = moment();
  const startDate = moment().subtract(6, 'days');
  dateRange.value = [
    startDate.format('YYYY-MM-DD'),
    endDate.format('YYYY-MM-DD')
  ];
};

const getStatistics = async () => {
  try {
    loading.value = true;
    const params = {
      start_date: dateRange.value[0],
      end_date: dateRange.value[1],
      chart_type: activeChartTab.value
    };
    
    const res = await fetchCouponStatistics(params);
    
    // 更新概览数据
    Object.assign(overviewData, res.overview || {});
    
    // 更新图表数据
    chartData.value = res.chart_data || [];
    
    // 更新详细统计
    typeStats.value = res.type_stats || [];
    storeStats.value = res.store_stats || [];
    timeStats.value = res.time_stats || [];
    
  } catch (error) {
    console.error('获取统计数据失败:', error);
    uni.showToast({
      title: '获取数据失败',
      icon: 'none'
    });
  } finally {
    loading.value = false;
    uni.stopPullDownRefresh();
  }
};

const handleFilter = () => {
  if (!dateRange.value || dateRange.value.length !== 2) {
    uni.showToast({
      title: '请选择时间范围',
      icon: 'none'
    });
    return;
  }
  getStatistics();
};

const switchChartTab = (tab: string) => {
  activeChartTab.value = tab;
  getStatistics();
};

const getBarHeight = (value: number) => {
  const maxValue = Math.max(...chartData.value.map(item => item.value));
  return maxValue > 0 ? (value / maxValue) * 120 : 0;
};

const getTimeBarHeight = (count: number) => {
  const maxCount = Math.max(...timeStats.value.map(item => item.count));
  return maxCount > 0 ? (count / maxCount) * 100 : 0;
};

const getRankClass = (index: number) => {
  if (index === 0) return 'first';
  if (index === 1) return 'second';
  if (index === 2) return 'third';
  return '';
};

onLoad(() => {
  initDateRange();
  getStatistics();
});

onPullDownRefresh(() => {
  getStatistics();
});
</script>

<style lang="scss" scoped>
.page-container {
  min-height: 100vh;
  background-color: var(--background-color);
}

.filter-bar {
  display: flex;
  align-items: center;
  padding: 15px;
  background-color: #fff;
  border-bottom: 1px solid var(--border-color);
  
  .time-filter {
    flex: 1;
    margin-right: 15px;
    
    .date-input {
      display: flex;
      align-items: center;
      padding: 8px 12px;
      background-color: var(--background-color);
      border-radius: var(--border-radius);
      border: 1px solid var(--border-color);
      
      .date-text {
        margin-left: 8px;
        font-size: 14px;
        color: var(--text-color-primary);
      }
    }
  }
  
  .filter-btn {
    padding: 8px 20px;
    background-color: var(--primary-color);
    color: #fff;
    border: none;
    border-radius: var(--border-radius);
    font-size: 14px;
  }
}

.overview-stats {
  padding: 15px;
  
  .stats-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 15px;
    
    .stats-card {
      display: flex;
      align-items: center;
      background-color: #fff;
      border-radius: var(--border-radius-lg);
      padding: 20px;
      box-shadow: var(--shadow);
      
      .stats-icon {
        width: 50px;
        height: 50px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 15px;
        
        &.coupon-icon {
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        
        &.issued-icon {
          background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
        }
        
        &.used-icon {
          background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
        }
        
        &.rate-icon {
          background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
        }
      }
      
      .stats-content {
        flex: 1;
        
        .stats-value {
          display: block;
          font-size: 20px;
          font-weight: bold;
          color: var(--text-color-primary);
          margin-bottom: 4px;
        }
        
        .stats-label {
          font-size: 12px;
          color: var(--text-color-secondary);
        }
      }
    }
  }
}

.chart-section {
  margin: 15px;
  background-color: #fff;
  border-radius: var(--border-radius-lg);
  padding: 20px;
  box-shadow: var(--shadow);
  
  .section-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    text {
      font-size: 16px;
      font-weight: bold;
      color: var(--text-color-primary);
    }
    
    .chart-tabs {
      display: flex;
      
      .chart-tab {
        padding: 6px 12px;
        font-size: 12px;
        color: var(--text-color-secondary);
        border-radius: var(--border-radius);
        margin-left: 8px;
        
        &.active {
          background-color: var(--primary-color);
          color: #fff;
        }
      }
    }
  }
  
  .chart-container {
    height: 200px;
    
    .empty-chart {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      height: 100%;
      
      .empty-text {
        margin-top: 10px;
        color: #999;
        font-size: 14px;
      }
    }
    
    .chart-content {
      height: 100%;
      display: flex;
      flex-direction: column;
      
      .simple-chart {
        flex: 1;
        display: flex;
        align-items: flex-end;
        justify-content: space-around;
        padding: 0 10px;
        
        .chart-bar {
          width: 30px;
          background: linear-gradient(180deg, var(--primary-color) 0%, rgba(24, 144, 255, 0.3) 100%);
          border-radius: 4px 4px 0 0;
          position: relative;
          min-height: 10px;
          
          .bar-value {
            position: absolute;
            top: -20px;
            left: 50%;
            transform: translateX(-50%);
            font-size: 10px;
            color: var(--text-color-secondary);
          }
        }
      }
      
      .chart-labels {
        display: flex;
        justify-content: space-around;
        padding: 10px;
        
        .chart-label {
          font-size: 10px;
          color: var(--text-color-secondary);
        }
      }
    }
  }
}

.detail-stats {
  padding: 0 15px 15px;
  
  .section-title {
    font-size: 16px;
    font-weight: bold;
    color: var(--text-color-primary);
    margin-bottom: 15px;
  }
  
  .stats-item {
    background-color: #fff;
    border-radius: var(--border-radius-lg);
    margin-bottom: 15px;
    box-shadow: var(--shadow);
    
    .item-header {
      padding: 15px 20px;
      border-bottom: 1px solid var(--border-color);
      
      .item-title {
        font-size: 14px;
        font-weight: bold;
        color: var(--text-color-primary);
      }
    }
    
    .item-content {
      padding: 15px 20px;
      
      .stat-row {
        display: flex;
        align-items: center;
        margin-bottom: 15px;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .stat-info {
          flex: 1;
          
          .stat-name {
            display: block;
            font-size: 14px;
            color: var(--text-color-primary);
            margin-bottom: 4px;
          }
          
          .stat-desc {
            font-size: 12px;
            color: var(--text-color-secondary);
          }
        }
        
        .stat-progress {
          width: 80px;
          height: 6px;
          background-color: var(--background-color);
          border-radius: 3px;
          overflow: hidden;
          
          .progress-bar {
            height: 100%;
            background-color: var(--primary-color);
            border-radius: 3px;
          }
        }
      }
      
      .rank-row {
        display: flex;
        align-items: center;
        margin-bottom: 15px;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .rank-number {
          width: 24px;
          height: 24px;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 12px;
          font-weight: bold;
          margin-right: 15px;
          background-color: #f0f0f0;
          color: #999;
          
          &.first {
            background-color: #ffd700;
            color: #fff;
          }
          
          &.second {
            background-color: #c0c0c0;
            color: #fff;
          }
          
          &.third {
            background-color: #cd7f32;
            color: #fff;
          }
        }
        
        .rank-info {
          flex: 1;
          
          .rank-name {
            display: block;
            font-size: 14px;
            color: var(--text-color-primary);
            margin-bottom: 4px;
          }
          
          .rank-desc {
            font-size: 12px;
            color: var(--text-color-secondary);
          }
        }
        
        .rank-amount {
          font-size: 14px;
          font-weight: bold;
          color: var(--primary-color);
        }
      }
      
      .time-distribution {
        display: flex;
        justify-content: space-between;
        align-items: flex-end;
        height: 120px;
        
        .time-bar {
          display: flex;
          flex-direction: column;
          align-items: center;
          flex: 1;
          
          .time-label {
            font-size: 10px;
            color: var(--text-color-secondary);
            margin-bottom: 8px;
          }
          
          .time-progress {
            width: 20px;
            height: 80px;
            background-color: var(--background-color);
            border-radius: 10px;
            position: relative;
            margin-bottom: 8px;
            
            .time-fill {
              position: absolute;
              bottom: 0;
              left: 0;
              right: 0;
              background: linear-gradient(180deg, var(--primary-color) 0%, rgba(24, 144, 255, 0.3) 100%);
              border-radius: 10px;
            }
          }
          
          .time-count {
            font-size: 10px;
            color: var(--text-color-primary);
            font-weight: bold;
          }
        }
      }
    }
  }
}
</style>